package servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.QueryUtil;

import beans.Query;


/**
 * Servlet implementation class PortalEntry
 */
@WebServlet("/PortalEntry")
public class PortalEntry extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public PortalEntry() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		
		ArrayList<Query> queries = (ArrayList<Query>) request.getSession().getAttribute("queries");
		if(queries == null)
			queries = new ArrayList<Query>();
		
		if("delete".equals(request.getParameter("do"))) {
			
			try {
				queries.remove(Integer.parseInt(request.getParameter("id")));		
			} catch( Exception e) {
				//hehe
			}
		}
		if("add".equals(request.getParameter("do"))) {
			Query query = new Query();
			String word = request.getParameter("word");
			
			query.setWord(word);
			query.setQuantifier(request.getParameter("quantifier"));
			if(!"Wybierz...".equals(word))
				queries.add(query);		
		}
		if("search".equals(request.getParameter("do"))) {
		
			QueryUtil util= new QueryUtil();
			List<String> cond= new ArrayList<String>();
			for(Query q : queries) {
				cond.add(q.getQuantifier() + q.getWord());
			}
			if(!cond.isEmpty()) 	{		
				ArrayList<String> results = (ArrayList<String>) util.executeQuery(cond);
				request.getSession().setAttribute("results", results);
			}
		}
		request.getSession().setAttribute("queries", queries);
		getServletContext().getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request, response);
	}

}
